<template>
	<view class="container">
		<view class="line-chart">
			<view class="mar-bot20">
				<!-- 3.0最新版本修改 -->
				<view class="abs">
					<!-- <view class="inline-block" v-for="(items,indx) in lineColorArr" :key="indx">
						<view :style="{color: items.color}" @tap="tapclick(indx,'line')">● 折线{{indx+1}}</view>
					</view> -->
				</view>
				<canvas @touchstart="onClick" class="chart" id="line" canvas-id="line"></canvas>
			</view>
		</view>
		<view class="scroll-box">
			<view class="scroll-title">
				<view>患者姓名</view>
				<view>训练得分</view> 
			</view>
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
				@scrolltolower="lower" @scroll="scroll">
				<view id="demo1" class="scroll-view-item uni-bg-red" v-for="(item,index) in dataList" :key="index">
					<view>{{item.name}}</view>
					<view class="score">{{item.score}}</view>
				</view>
			
			</scroll-view>
			<!-- <view class="back">返回</view> -->
		</view>
		<view class="back" style="margin-top: 40rpx;font-size: 20px;text-align: center;" @click="back">返回</view>
	</view>

</template>



<script>
	import uCharts from '@/components/leiqch-ucharts/u-charts.vue';
	import crt from '@/components/leiqch-ucharts/js/chartsUtil.js';

	export default {
		data() {
			return {
				canvas: true,
				cWidth: '',
				cHeight: '',
				arr: [],
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				lineColorArr: [{
					color: "#ffffff"
				}, {
					color: "#ffffff"
				}], //切换折线1，折线2{color:"#888"},{color:"#888"}3.0最新版本修改
				history:[],
                dataList:[],
				dataX:[],
				dataY:[],
			}
		},
		components: {
			uCharts
		},
		onLoad(e) {
			this.getRank();
		},
		onReady() {
			uni.showLoading({
				title:"加载中"
			})
			const query = uni.createSelectorQuery().in(this);
			query.select('.chart').boundingClientRect(data => {
				this.domEchart = data;
				this.lineDraw("line", data, -1);
			}).exec();
			uni.hideLoading()
		},
		methods: {
			back(){
				uni.navigateBack({
					delta:1
				})
			},
			
			getRank(){
				var me=this;
				var usertoken = uni.getStorageSync("usertoken");
				var info = uni.getStorageSync("accountInfo");
                // console.log(info)
				uni.request({
					url: me.serverUrl + "/train/getGameScore",
					data: {
						"phoneNum": info.phone
					},
					method: "POST",
					header: {
						"usertoken": usertoken
					},
					success(res) {
						console.log(res.data)
						// var data = JSON.parse(res.data)
						// console.log(data)
						if (res.data.status == 200) {
							console.log("获取游戏历史记录成功")
                            me.dataList = res.data["data"]["rankList"];
							
							// me.dataX=res.data.x;
							// me.dataY=res.data.y;
                            
							console.log(me.dataList)
							// console.log(me.listH)
							// me.trainScore=res.data.trainScore;
							// me.percent=res.data.percent;
						}
					}
				})
			},
			upper: function(e) {
				console.log(e)
			},
			lower: function(e) {
				console.log(e)
			},
			scroll: function(e) {
				console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			goTop: function(e) {
				this.scrollTop = this.old.scrollTop
				this.$nextTick(() => {
					this.scrollTop = 0
				});
				uni.showToast({
					icon: "none",
					title: "纵向滚动 scrollTop 值已被修改为 0"
				})
			},
			init() {
				// this.cWidth = uni.upx2px(750);
				this.cWidth = uni.upx2px(700);
				this.cHeight = uni.upx2px(400);
				this.getServerData();
				this.query()
			},
			query() {
				// this.findFamilyQYByList()
			},
			jump(url, title = '', to = 3) {
				// this.$api.jump(url,title,to)
			},
			change(idx, type, etype) {
				this.$refs[this.arr[idx].id][0].changeData(this.arr[idx].id, this.arr[idx].opts, type, etype)
			},
			//求两点之间的距离3.0最新版本修改
			distDot(pointA, pointB, R) {
				return Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2)) - R
			},
			toFixedNumber(n = 2, val) { //去小数点后2位
				if (typeof val == "number") {
					return val.toFixed(n) * 1
				}
			},
			//切换line，bar的每个lengend点击事件3.0最新版本修改
			tapclick(n, ids) {
				this.tapEvent = null;
				if (ids == "line") {
					this.lineDraw(ids, this.domEchart, n);
				} else if (ids == "bar") {
					this.barDraw3d("bar", this.domEchart, n);
				}
				// console.log("this", this);
			},
			//点击 事件line，bar3.0最新版本修改
			onClick(ev) {
				let obj = ev.target;
				if (ev.type == "touchstart") {
					obj.x = ev.touches[0].x;
					obj.y = ev.touches[0].y;
					obj.offsetLeft = 0;
					obj.offsetTop = 0;
				}
				this.tapEvent = obj;
				if (obj.id == "line") {
					this.lineDraw(obj.id, this.domEchart, -1);
				} else if (obj.id == "bar") {
					this.barDraw3d(obj.id, this.domEchart, -1);
				}
			},
			//绘制线条 line chart3.0最新版本修改
			lineDraw(ids, elem, num = -1) {
				let ctx = uni.createCanvasContext(ids),
					isHover = null;
				let grid = {
						top: (12 * elem.height) / 100, //canvas标签的高度的12%（相对总高的百分比）
						bottom: ((100 - 18) * elem.height) / 100, //canvas图形距离底部的百分比 18%
						left: (12 * elem.width) / 100, //距离左侧的百分比（12%总宽度）
						right: ((100 - 8) * elem.width) / 100 //距离右侧百分比（8%总宽度）
					},
					lineColor = "#FFFFFF", //x,y轴线颜色
					fillColor = "#FFFFFF", //x,y轴number颜色
					yAxis = {
						textSize: 15, //刻度数字fontSize
						maxNumber: 900, //分段的最大值
						splitNumber: 6, //分成几段
						splitLen: 5, //轴左侧的小横线 -|
						marginSplit: 5 //刻度文字与 “-|”的距离  
					},
					lineWidth = 1,
					xAxis = {
						textSize: 15, //刻度数字fontSize
						maxNumber: 12,
						splitNumber: 6,
						splitLen: 5,
						marginSplit: 5
					},
					dotStyle = [{
						color: "#fff",
						arcR: 4, //半径
						dash: 0 //是否线条虚线 0实线 1以上虚线
					}],
					lineStyle = [{
						color: "#ffffff",
						lineDotType: "wave", //两圆点的连接线 line直线，wave二次贝塞尔曲线
						width: 2, //连线的width
						dash: 0 //是否线条虚线 0实线 1以上虚线
					}],
					dataJSON = [ //数据data
						{
							x:this.dataX,
							y:this.dataY
							// x: ["21日", "22日", "23日", "24日", "25日", "26日"], //设置字符类型，非Number
							// y: [169, 228, 370, 365, 376, 465]
						},
					];
				lineStyle.forEach((ep, vp) => {
					if (num == vp) {
						this.lineColorArr[vp] = {
							color: ep.color
						};
					} else if (num == -1) {
						this.lineColorArr[vp] = {
							color: ep.color
						};
					} else {
						this.lineColorArr[vp] = {
							color: "#888"
						};
					}

				});
				ctx.beginPath();
				ctx.setLineWidth(lineWidth);
				ctx.setTextAlign("right");
				ctx.setTextBaseline("middle");
				ctx.setStrokeStyle(lineColor);
				ctx.setFillStyle(fillColor);
				ctx.moveTo(grid.left, grid.top);
				ctx.lineTo(grid.left, grid.bottom);
				ctx.setFontSize(yAxis.textSize);
				for (let n = 1; n <= yAxis.splitNumber; n++) {
					ctx.moveTo(grid.left, grid.bottom - (grid.bottom - grid.top) / yAxis.splitNumber * n + lineWidth);
					ctx.lineTo(grid.left - yAxis.splitLen, grid.bottom - (grid.bottom - grid.top) / yAxis.splitNumber * n +
						lineWidth);
					ctx.fillText(this.toFixedNumber(1, yAxis.maxNumber / yAxis.splitNumber * n), grid.left - yAxis
						.splitLen - lineWidth - yAxis.marginSplit, grid.bottom - (grid.bottom - grid.top) / yAxis
						.splitNumber * n + lineWidth)
				}
				ctx.moveTo(grid.left, grid.bottom);
				ctx.lineTo(grid.right, grid.bottom);
				ctx.setTextAlign("center");
				ctx.setTextBaseline("top");
				ctx.setFontSize(xAxis.textSize);
				if (typeof dataJSON[0].x[0] != "number") { //非number类型数据
					xAxis.splitNumber = dataJSON[0].x.length;
					xAxis.maxNumber = dataJSON[0].x.length;
				}
				for (let n = 1; n <= xAxis.splitNumber; n++) {
					ctx.moveTo(grid.left + (grid.right - grid.left) / xAxis.splitNumber * n - lineWidth, grid.bottom);
					ctx.lineTo(grid.left + (grid.right - grid.left) / xAxis.splitNumber * n - lineWidth, grid.bottom +
						xAxis.splitLen);
					//this.toFixedNumber(1, xAxis.maxNumber / xAxis.splitNumber * n)
					if (typeof dataJSON[0].x[n - 1] != "number") { //数据非number类型
						ctx.fillText(dataJSON[0].x[n - 1], grid.left + (grid.right -
								grid.left) / xAxis.splitNumber * n - lineWidth, grid.bottom + xAxis.splitLen +
							lineWidth +
							xAxis.marginSplit)
					} else { //number类型
						ctx.fillText(this.toFixedNumber(1, xAxis.maxNumber / xAxis.splitNumber * n), grid.left + (grid
								.right -
								grid.left) / xAxis.splitNumber * n - lineWidth, grid.bottom + xAxis.splitLen +
							lineWidth +
							xAxis.marginSplit)
					}
				}
				ctx.stroke();
				let tapDraw = (obj, data) => {
					ctx.save();
					ctx.beginPath();
					ctx.setFillStyle("#2C405A");
					ctx.setStrokeStyle("#4DA1FE");
					ctx.setLineDash([5]);
					ctx.setLineWidth(1);
					ctx.moveTo(grid.left, obj.y - obj.offsetTop);
					ctx.lineTo(grid.right, obj.y - obj.offsetTop);
					ctx.moveTo(obj.x - obj.offsetLeft, grid.top);
					ctx.lineTo(obj.x - obj.offsetLeft, grid.bottom);
					ctx.stroke();
					ctx.restore();
					// ctx.draw(true, function(res,obj){
					// 	console.log('draw success', ctx);
					// });
				}
				let drawLineData = (dataX, dataY, ix) => {
					dataX.forEach((ele, indx) => {
						let x, y;
						if (typeof ele !== "number") {
							x = grid.left + (grid.right - grid.left) * ((indx + 1) / xAxis.maxNumber) -
								lineWidth,
								y = grid.bottom - (grid.bottom - grid.top) * (dataY[indx] / yAxis.maxNumber) +
								lineWidth;
						} else {
							x = grid.left + (grid.right - grid.left) * (ele / xAxis.maxNumber) - lineWidth,
								y = grid.bottom - (grid.bottom - grid.top) * (dataY[indx] / yAxis.maxNumber) +
								lineWidth;
						}
						if (indx >= dataX.length - 1) {} else {
							let x2 = typeof ele !== "number" ? grid.left + (grid.right - grid.left) * ((indx +
										2) / xAxis
									.maxNumber) - lineWidth : grid.left + (grid.right - grid.left) * (dataX[
										indx + 1] / xAxis
									.maxNumber) - lineWidth,
								y2 = grid.bottom - (grid.bottom - grid.top) * (dataY[indx + 1] / yAxis
									.maxNumber) + lineWidth;
							let dis = {
								x: x + (x2 - x) / 3 + (x2 - x) / 2,
								y: y2 - y > 0 ? y + (y2 - y) / 3 - (y2 - y) / 5 : y + (y2 - y) / 3 + (y2 -
									y) / 5
							};
							ctx.beginPath();
							ctx.setStrokeStyle(lineStyle[ix].color);
							ctx.setLineDash([lineStyle[ix].dash]);
							ctx.moveTo(x, y);
							if (lineStyle[ix].lineDotType == "line") { //直线连接
								ctx.lineTo(x2, y2);
							} else if (lineStyle[ix].lineDotType == "wave") { //二次贝塞尔曲线连接
								ctx.quadraticCurveTo(dis.x, dis.y, x2, y2);
							}
							ctx.stroke();
						}
						//显示 x，y的值
						if (this.tapEvent != null) {
							let x2 = this.tapEvent.x - this.tapEvent.offsetLeft,
								y2 = this.tapEvent.y - this.tapEvent.offsetTop;
							if (this.distDot({
									x: x2,
									y: y2
								}, {
									x: x,
									y: y
								}, dotStyle[ix].arcR + lineWidth) < 0) {
								ctx.beginPath();
								ctx.setFillStyle("#4DA1FE");
								ctx.setLineDash([dotStyle[ix].dash]);
								ctx.arc(x, y, dotStyle[ix].arcR * 1.5, 0, 2 * Math.PI);
								ctx.fill();
								ctx.stroke();

								ctx.beginPath();
								ctx.setFillStyle(lineStyle[ix].color);
								ctx.setFontSize(14);
								ix % 2 == 1 ?
									ctx.fillText(ele + "," + dataY[indx], x, y + 6) :
									ctx.fillText(ele + "," + dataY[indx], x, y - 20);
								isHover = {
									x: x,
									y: y
								};
								ctx.fill();
							} else {
								ctx.beginPath();
								ctx.setFillStyle(dotStyle[ix].color);
								ctx.setLineDash([dotStyle[ix].dash]);
								ctx.arc(x, y, dotStyle[ix].arcR, 0, 2 * Math.PI);
								ctx.fill();
								ctx.stroke();
							}

						} else {
							ctx.beginPath();
							ctx.setFillStyle(dotStyle[ix].color);
							ctx.setLineDash([dotStyle[ix].dash]);
							ctx.arc(x, y, dotStyle[ix].arcR, 0, 2 * Math.PI);
							ctx.fill();
							ctx.stroke();
							if (num != -1) {
								ctx.beginPath();
								ctx.setFillStyle(lineStyle[ix].color);
								ctx.setFontSize(12);
								ctx.fillText(ele + "," + dataY[indx], x, y + 6);
								ctx.fill();
							}
						}
					})
				}
				dataJSON.forEach((e, v) => {
					if (v == num && num != -1) {
						drawLineData(e.x, e.y, v);
					} else if (num == -1) {
						drawLineData(e.x, e.y, v);
					} else {

					}
				})
				if (this.tapEvent != null && isHover != null) {
					tapDraw(this.tapEvent, elem);
				}
				ctx.draw();
			},
		}
	}
</script>

<style>
	@import url("history-train-data.css");
</style>
